//
//  AppDelegate.m
//  BeidouMall
//
//  Created by qie on 16/3/28.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "AppDelegate.h"
#import "BDPoint.h"
#import "BDLineSegment.h"

#define PI 3.1415926
#define MyINFINITY 0.00000000001
#define ESP 0.000001

@interface AppDelegate () <BMKLocationServiceDelegate>
{
    BMKMapManager* _mapManager;
    
    NSTimer *_timer;
    BMKLocationService *_locService;
}
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [NSThread sleepForTimeInterval:2.0];
    //请先启动BaiduMapManager
    _mapManager = [[BMKMapManager alloc]init];
    // 如果要关注网络及授权验证事件，请设定generalDelegate参数
    BOOL ret = [_mapManager start:Map_ak  generalDelegate:nil];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc] init];
    _locService.delegate = self;
    [self startLocation];
    
    // 设置状态栏样式
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    [_timer invalidate];
    _timer = nil;
    
    NSURLCache * cache = [NSURLCache sharedURLCache];
    [cache removeAllCachedResponses];
    [cache setDiskCapacity:0];
    [cache setMemoryCapacity:0];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     _timer = [NSTimer scheduledTimerWithTimeInterval:600.0 target:self selector:@selector(startLocation) userInfo:nil repeats:YES];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    
    //如果极简开发包不可用，会跳转支付宝钱包进行支付，需要将支付宝钱包的支付结果回传给开发包
    if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            //【由于在跳转支付宝客户端支付的过程中，商户app在后台很可能被系统kill了，所以pay接口的callback就会失效，请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】
            NSLog(@"result = %@",resultDic);
        }];
    }
    if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回authCode
        
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
            //【由于在跳转支付宝客户端支付的过程中，商户app在后台很可能被系统kill了，所以pay接口的callback就会失效，请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】
            NSLog(@"result = %@",resultDic);
        }];
    }
    return YES;
}

#pragma mark BMKLocationServiceDelegate

//处理方向变更信息
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    //NSLog(@"heading is %@",userLocation.heading);
}
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    [BDAccountManagerModel shareInstance].latitude = userLocation.location.coordinate.latitude;
    [BDAccountManagerModel shareInstance].longitude = userLocation.location.coordinate.longitude;
}

- (void)geoCoding {
    NSString *urlStr = [NSString stringWithFormat:@"http://api.map.baidu.com/geocoder/v2/?ak=Sxu7ULwGKHYFTmsyyNR3GlGwxrBnQEcK&callback=renderReverse&location=%f,%f&output=json&pois=0&mcode=com.doudou.BeidouMall",[BDAccountManagerModel shareInstance].latitude,[BDAccountManagerModel shareInstance].longitude];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    request.HTTPMethod = @"GET";
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error != nil) {
            NSLog(@"error = %@",[error localizedDescription]);
        } else {
            NSObject *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"json = %@",json);
            NSString *jsonStr = (NSString *)json;
            NSArray *arr = [jsonStr componentsSeparatedByString:@"("];
            jsonStr = arr[1];
            arr = [jsonStr componentsSeparatedByString:@")"];
            jsonStr = arr[0];
            NSDictionary *dic = [NSString dictionaryWithJsonString:jsonStr];
            if ([dic valueForKey:@"result"]) {
                dic = dic[@"result"];
                NSInteger cityCode = [[dic valueForKey:@"cityCode"] integerValue];
                [BDAccountManagerModel shareInstance].cityCode = cityCode;
            }
        }
    }];
    [task resume];
}

#pragma mark Private method

- (double)lantitudeLongitudeDist:(double)lon1 other_Lat:(double)lat1 self_Lon:(double)lon2 self_Lat:(double)lat2 {
    double er = 6378137; // 6378700.0f;
    //ave. radius = 6371.315 (someone said more accurate is 6366.707)
    //equatorial radius = 6378.388
    //nautical mile = 1.15078
    double radlat1 = PI*lat1/180.0f;
    double radlat2 = PI*lat2/180.0f;
    //now long.
    double radlong1 = PI*lon1/180.0f;
    double radlong2 = PI*lon2/180.0f;
    if( radlat1 < 0 ) radlat1 = PI/2 + fabs(radlat1);// south
    if( radlat1 > 0 ) radlat1 = PI/2 - fabs(radlat1);// north
    if( radlong1 < 0 ) radlong1 = PI*2 - fabs(radlong1);//west
    if( radlat2 < 0 ) radlat2 = PI/2 + fabs(radlat2);// south
    if( radlat2 > 0 ) radlat2 = PI/2 - fabs(radlat2);// north
    if( radlong2 < 0 ) radlong2 = PI*2 - fabs(radlong2);// west
    //spherical coordinates x=r*cos(ag)sin(at), y=r*sin(ag)*sin(at), z=r*cos(at)
    //zero ag is up so reverse lat
    double x1 = er * cos(radlong1) * sin(radlat1);
    double y1 = er * sin(radlong1) * sin(radlat1);
    double z1 = er * cos(radlat1);
    double x2 = er * cos(radlong2) * sin(radlat2);
    double y2 = er * sin(radlong2) * sin(radlat2);
    double z2 = er * cos(radlat2);
    double d = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)+(z1-z2)*(z1-z2));
    //side, side, side, law of cosines and arccos
    double theta = acos((er*er+er*er-d*d)/(2*er*er));
    double dist  = theta*er;
    return dist;
}

- (double)maxWithX:(double)x Y:(double)y {
    return x >= y ? x : y;
}

- (double)minWithX:(double)x Y:(double)y {
    return x >= y ? y : x;
}

- (double)MultiplyWithPoint1:(BDPoint *)p1 Point2:(BDPoint *)p2 Point0:(BDPoint *)p0 {
    return ( (p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) * (p1.y - p0.y) );
}

- (BOOL)IsOnlineWithPoint:(BDPoint *)point LineSegment:(BDLineSegment *)line {
    
    return( (fabs([self MultiplyWithPoint1:line.pt1 Point2:line.pt2 Point0:point]) < ESP ) &&
           
           ( ( point.x - line.pt1.x ) * ( point.x - line.pt2.x ) <= 0 ) &&
           
           ( ( point.y - line.pt1.y ) * ( point.y - line.pt2.y ) <= 0 ) );
}

- (BOOL)IntersectWithLineSegment1:(BDLineSegment *)L1 LineSegment2:(BDLineSegment *)L2 {
    return( ([self maxWithX:L1.pt1.x Y:L1.pt2.x] >= [self minWithX:L2.pt1.x Y:L2.pt2.x]) &&
           
           ([self maxWithX:L2.pt1.x Y:L2.pt2.x] >= [self minWithX:L1.pt1.x Y:L1.pt2.x]) &&
           
           ([self maxWithX:L1.pt1.x Y:L1.pt2.x] >= [self minWithX:L2.pt1.x Y:L2.pt2.x]) &&
           
           ([self maxWithX:L2.pt1.x Y:L2.pt2.x] >= [self minWithX:L1.pt1.x Y:L1.pt2.x]) &&
           
           ([self MultiplyWithPoint1:L2.pt1 Point2: L1.pt2 Point0:L1.pt1] * [self MultiplyWithPoint1:L1.pt2 Point2: L2.pt2 Point0:L1.pt1] >= 0) &&
           
           ([self MultiplyWithPoint1:L1.pt1 Point2: L2.pt2 Point0:L2.pt1] * [self MultiplyWithPoint1:L2.pt2 Point2: L1.pt2 Point0:L2.pt1] >= 0)
           
           );
}

/* 射线法判断点q与多边形polygon的位置关系，要求polygon为简单多边形，顶点逆时针排列
 如果点在多边形内： 返回0
 如果点在多边形边上： 返回1
 如果点在多边形外： 返回2
*/
- (int)InPolygonWithList:(NSArray *)polygon Point:(BDPoint *)point {
    NSInteger n = polygon.count;
    int count = 0;
    BDLineSegment *line = [[BDLineSegment alloc] init];
    line.pt1 = point;
    line.pt2.y = point.y;
    line.pt2.x = - MyINFINITY;
    for( int i = 0; i < n; i++) {
        BDLineSegment *side = [[BDLineSegment alloc] init];
        side.pt1 = polygon[i];
        side.pt2 = polygon[(i + 1) % n];
        if ([self IsOnlineWithPoint:point LineSegment:side]) {
            return 1;
        }
        if (fabs(side.pt1.y - side.pt2.y) < ESP) {
            continue;
        }
        if ([self IsOnlineWithPoint:side.pt1 LineSegment:line]) {
            if( side.pt1.y > side.pt2.y ) {
                count++;
            }
        } else if ([self IsOnlineWithPoint:side.pt2 LineSegment:line]) {
            if( side.pt2.y > side.pt1.y ) {
                count++;
            }
        } else if ([self IntersectWithLineSegment1:line LineSegment2:side]) {
            count++;
        }
    }
    return  count % 2 == 1 ? 0 : 2;
}

- (void)startLocation {
    //启动LocationService
    [_locService startUserLocationService];
    //2秒后停止位置更新
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [_locService stopUserLocationService];
//        double distance = [self lantitudeLongitudeDist:[BDAccountManagerModel shareInstance].longitude other_Lat:[BDAccountManagerModel shareInstance].latitude self_Lon:101.964328 self_Lat:30.04961];
//        NSLog(@"distance = %f",distance);
//        if (distance <= 3000.0) {
//            [BDAccountManagerModel shareInstance].inBoundary = @"yes";
//        } else {
//            [BDAccountManagerModel shareInstance].inBoundary = @"no";
//        }
        BDPoint *point1 = [[BDPoint alloc] initWithX:3.0 andY:5.0];
        BDPoint *point2 = [[BDPoint alloc] initWithX:3.0 andY:3.0];
        BDPoint *point3 = [[BDPoint alloc] initWithX:1.0 andY:1.0];
        BDPoint *point4 = [[BDPoint alloc] initWithX:4.0 andY:0.0];
        BDPoint *point5 = [[BDPoint alloc] initWithX:5.0 andY:3.0];
        NSArray *polygon = @[point1,point2,point3,point4,point5];
        int num = 0;
        for(int i=1;i<=5;i++){
            for(int j=0;j<=5;j++){
                if ([self InPolygonWithList:polygon Point:
                     [[BDPoint alloc] initWithX:i andY:j]] == 2) {
                    ++num;
                    NSLog(@"(%d,%d)num=%d",i,j,num);
                }
                
            }
        }
    });
}



@end
